package com.ruoyi.web.ydz.util.quartz;

import cn.hutool.json.JSONUtil;
import com.ruoyi.web.ydz.domain.MedicationReminder;
import com.ruoyi.web.ydz.mapper.MedicationReminderMapper;
import com.ruoyi.web.ydz.util.websocket.WebSocketUsers;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

@Component
public class TaskJob implements Job {

    @Resource
    private MedicationReminderMapper medicationReminderMapper;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("定时任务执行:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        JobDetail jobDetail = jobExecutionContext.getJobDetail();

        /*获取任务中的 提醒用药ID 与前端进行互动 提醒用户*/
        if (!Objects.isNull(jobDetail.getJobDataMap().get("medicationReminderId"))) {
            Long medicationReminderId = Long.parseLong(String.valueOf(jobDetail.getJobDataMap().get("medicationReminderId")));

            /*获取当前提醒用药对象*/
            if (!Objects.isNull(medicationReminderId)) {

                System.out.println("提醒用药ID:" + medicationReminderId);

                MedicationReminder medicationReminder = medicationReminderMapper.selectMedicationReminderById(medicationReminderId);
                /*发送信息*/
                WebSocketUsers.sendMessageToUser(medicationReminder.getCreateBy(), JSONUtil.toJsonStr(medicationReminder));

            } else {
                System.out.println("未获取到有效提醒用药ID");
            }
        } else {
            System.out.println("未获取到提醒用药ID");
        }
    }
}
